﻿using Core.Toolkit;
using Core.Toolkit.ActionResultHelp;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;

namespace Core.SimpleTemp.Common
{
    public static class ExceptionHelp
    {
        public static IActionResult CreateErrorResponse(Exception exception, bool isDevelopment, string traceIdentifier)
        {

            var jsonErrorResponse = CreateErrorJson(exception, isDevelopment, traceIdentifier);
            return new InternalServerErrorObjectResult(jsonErrorResponse);
        }

        public static JsonErrorResponse CreateErrorJson(Exception exception, bool isDevelopment, string traceIdentifier)
        {
            var json = new JsonErrorResponse();
            json.result = SysConsts.AJAX_RESULT_FAILD;
            if (exception.GetType().IsSubclassOf(typeof(CustomOperationException)) || exception.GetType() == typeof(CustomOperationException))
            {
                json.message = $"{exception.Message}[{traceIdentifier}]";
            }
            else
                json.message = $"发生内部未知错误[{traceIdentifier}]";

            if (isDevelopment)
                json.DeveloperMessage = exception.StackTrace;
            return json;
        }

        public class InternalServerErrorObjectResult : ObjectResult
        {
            public InternalServerErrorObjectResult(object error) : base(error)
            {
                StatusCode = StatusCodes.Status500InternalServerError;
            }
        }
    }
}
